/*
 * pid_controller.h
 *
 *  Created on: 10 sept. 2014
 *      Author: MarioC
 */

#ifndef PID_CONTROLLER_H_
#define PID_CONTROLLER_H_

#include <stdint.h>
#include <stdbool.h>

#define REAL_SGN(r)   (r >= 0) ? 1 : -1

typedef struct {
	union {
		uint16_t		raw;
		struct {
			uint16_t	fract_part : 8;
			uint16_t	int_part : 3;
			uint16_t	sgn : 1;
			uint16_t	reserved : 4;
		} bits_t;
	};
} s3_8_t;

typedef struct{
  uint32_t  error_thresh;
  uint32_t  h;
  s3_8_t  	kp;					// format a3.8 - 0x7FF = +1
  s3_8_t    ki;					// format a3.8 - 0x7FF = +1
  s3_8_t    kd;					// not available
  uint32_t	set_point;		    // Set point
  bool		anti_windup;		// true if anti windup is enabled
}pid_params_t;

typedef struct{
	uint32_t         max;
	uint32_t         min;
}pid_limiter_t;

typedef struct{
  uint32_t     		prev_error;
  uint32_t     		inv_h;
  pid_params_t 		params;
  bool         		is_limited;
  double    		integral_buffer;
  uint32_t     		prev_result;
  pid_limiter_t		limiter;
}pid_ctrl_t;





extern void 	pid_init		    (pid_ctrl_t* pid, pid_params_t *pid_params, pid_limiter_t *limiter);
extern uint32_t	pid_update		    (pid_ctrl_t* pid, int32_t error, const pid_limiter_t* pid_limiter);

extern void 	float_to_s3_8_t	    (s3_8_t *out, float in);
extern void		s3_8_t_to_double	(double *out, s3_8_t *in);

#endif /* PID_CONTROLLER_H_ */
